package pro2;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Author: Ma JiBin
 * @Email: 1423553596@qq.com
 * @Date: 2018/9/21 10:49
 * @Description: 本机直接内存溢出实验
 * 使用unsafe.allocateMemory()方法申请分配内存
 * VM Args: -Xmx20M -XX:MaxDirectMemorySize=10M
 * 测试成功，出现java.lang.OutOfMemoryError异常
 */
public class DirectMemoryOOM {
    private static final int _1MB = 1024 * 1024;

    public static void main(String[] args) {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe;
        try {
            unsafe = (Unsafe) unsafeField.get(null);
            while (true) {
                unsafe.allocateMemory(_1MB);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}
